<?php

/**
 * This is the model class for table "product_image".
 *
 * The followings are the available columns in table 'product_image':
 * @property integer $id
 * @property integer $product_id
 * @property string $path
 * @property integer $featured
 * @property string $created_at
 * @property string $updated_at
 * @property integer $view_counter
 */
class ProductImage extends CActiveRecord {

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return ProductImage the static model class
     */
    public static function model($className=__CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return 'product_image';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('product_id, featured, view_counter', 'numerical', 'integerOnly' => true),
            array('path', 'length', 'max' => 255),
            array('featured,view_counter', 'default', 'value' => 0),
            array('created_at, updated_at', 'safe'),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, product_id, path, featured, created_at, updated_at, view_counter', 'safe', 'on' => 'search'),
        );
    }

    /**
     * set timestamp before save
     */
    public function beforeSave() {
        if ($this->isNewRecord) {
            $this->created_at = new CDbExpression('NOW()');
            $this->setFeatured();
        }
        $this->updated_at = new CDbExpression('NOW()');
        return parent::beforeSave();
    }

    public function setFeatured() {
        $criteria = new CDbCriteria;
        $criteria->addCondition(array('product_id=:product_id', 'featured=:featured'));
        $criteria->params = array(':product_id' => $this->product_id, ':featured' => 1);
        $productImages = ProductImage::model()->findAll($criteria);
        if ($productImages == null) {
            $this->featured = 1;
        }
    }

    public function beforeDelete() {
        if ($this->featured == 1) {
            $criteria = new CDbCriteria;
            $criteria->addCondition(array('product_id=:product_id', 'featured !=:featured'));
            $criteria->params = array(':product_id' => $this->product_id, ':featured' => 1);
            $productImages = ProductImage::model()->findAll($criteria);
            foreach ($productImages as $productImage) {
                $productImage->featured = 1;
                $productImage->update();
                break;
            }
        }
        return parent::beforeDelete();
    }

    /**
     * delete uploaded images after delete model
     */
    public function afterDelete() {
        $path = Yii::getPathOfAlias('webroot') . DIRECTORY_SEPARATOR . $this->path;
        unlink($path);
        return parent::afterDelete();
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'product' => array(self::BELONGS_TO, 'Product', 'product_id'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'id' => Yii::t('product', 'id'),
            'product_id' => Yii::t('product', 'productId'),
            'path' => Yii::t('product', 'path'),
            'featured' => Yii::t('product', 'featuredImage'),
            'created_at' => Yii::t('product', 'createdAt'),
            'updated_at' => Yii::t('product', 'updatedAt'),
            'view_counter' => Yii::t('product', 'viewCounter'),
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search() {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('id', $this->id);
        $criteria->compare('product_id', $this->product_id);
        $criteria->compare('path', $this->path, true);
        $criteria->compare('featured', $this->featured);
        $criteria->compare('created_at', $this->created_at, true);
        $criteria->compare('updated_at', $this->updated_at, true);
        $criteria->compare('view_counter', $this->view_counter);

        return new CActiveDataProvider($this, array(
                    'criteria' => $criteria,
                ));
    }

    /**
     * get all images path
     */
    public function getAllImagesPath() {
        $productImages = ProductImage::model()->findAll();
        $paths = array();
        foreach ($productImages as $productImage) {
            $paths[] = $productImage->path;
        }
        return $paths;
    }

    /**
     * check existed image path 
     */
    public function existedImagePath($path) {
        $result = false;
        try {
            $productImages = ProductImage::model()->findAll();
            foreach ($productImages as $productImage) {
                if ($productImage->path == $path) {
                    $result = true;
                    break;
                }
            }
        } catch (Exception $ex) {
            $result = true;
            echo $ex->getMessage();
        }
        return $result;
    }

    /**
     * delete all product images by product_id
     */
    public function deleteAllByProductID($id) {
        $criteria = new CDbCriteria;
        $criteria->condition = "product_id =:product_id";
        $criteria->params = array(':product_id' => $id);
        return ProductImage::model()->deleteAll($criteria);
    }

    /**
     * delete all ProductImage by Product
     * 
     */
    public function deleteAllByProduct($product) {
        $productImages = $product->productImages;
        foreach ($productImages as $productImage) {
            $deleted = $productImage->delete();
        }
    }

}